package com.wjk.blogs.service;

import com.wjk.blogs.NotFoundException;
import com.wjk.blogs.dao.BlogRepository;
import com.wjk.blogs.dao.CommentRepository;
import com.wjk.blogs.po.Blog;
import com.wjk.blogs.po.Comment;
import com.wjk.blogs.po.Tag;
import com.wjk.blogs.util.MarkDown;
import com.wjk.blogs.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService{

    @Autowired
    private BlogRepository blogRepository;
    @Autowired
    private CommentService commentService;
   /* @Autowired
    private CommentRepository commentRepository;*/


    @Transactional
    @Override
    public Blog getBlog(Long id) {
        return blogRepository.findById(id).get();
    }

    @Override
    public Blog getAndConvert(Long id) {
        Blog blog=blogRepository.findById(id).get();
        if (blog == null){
            throw new NotFoundException("该博客不存在");
        }
        Blog b=new Blog();
        BeanUtils.copyProperties(blog,b);
        String content=b.getContent();
        b.setContent(MarkDown.markdownToHtmlExtensions(content));
        return b;
    }

    @Transactional
    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            /*toPredicat方法:处理动态查询条件
            root:要查询的blog对象,可以获取表的一些字段(属性、名字这些)
            CriteriaQuery<?> query：一个查询条件的容器
            CriteriaBuilder criteriaBuilder：设置具体某一个条件的表达式*/
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList=new ArrayList<>();
                if (!"".equals(blog.getTitle()) && blog.getTitle() != null){
                    predicateList.add(criteriaBuilder.like(root.<String>get("title"),"%"+blog.getTitle()+"%"));
                }
                if (blog.getTypeId() != null){
                    predicateList.add(criteriaBuilder.equal(root.<String>get("type").get("id"),blog.getTypeId()));
                }
                if (blog.isRecommend()){
                    predicateList.add(criteriaBuilder.equal(root.<Boolean>get("recommend"),blog.isRecommend()));
                }
                query.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        },pageable);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogRepository.findAll(pageable);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable, Long tagId) {

        return blogRepository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                return criteriaBuilder.equal(root.join("tags").get("id"),tagId);
            }
        },pageable);
    }

    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort=Sort.by(Sort.Direction.DESC,"updateTime");
        Pageable pageable= PageRequest.of(0,size,sort);
        return blogRepository.findTop(pageable);
    }

    @Override
    public Map<String, List<Blog>> archiveBlog() {
        List<String> years = blogRepository.findGroupByYear();
        Map<String,List<Blog>> map=new HashMap<>();
        for(String year:years){
            map.put(year,blogRepository.findByYear(year));
        }
        return map;
    }

    @Override
    public Long countBlog() {
        return blogRepository.count();
    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
        return blogRepository.save(blog);
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {

        Blog blog1=blogRepository.findById(id).get();
        if(blog1 == null){
            throw new NotFoundException("该博客不存在");
        }
        blog.setCreateTime(blog1.getCreateTime());
        blog.setViews(blog1.getViews());

        BeanUtils.copyProperties(blog,blog1);//将blog中的内容复制到blog1中
        return blogRepository.save(blog1);
    }

    @Transactional
    @Override
    public void delete(Long id) {
        List<Comment> comments= commentService.listCommentByBlogId(id);
        //Queue<Comment> queCom = new LinkedList<>();
        for (Comment comment : comments) {
            commentService.deleteComment(comment.getId());
            /*if (comment.getParentComment()==null){
                commentService.deleteComment(comment.getId());
            }else {
                queCom.add(comment);
            }
        }
        while (!queCom.isEmpty()){
            commentService.deleteComment(queCom.poll().getId());*/
        }
        //commentService.listCommentByBlogId(id);
        blogRepository.deleteById(id);

    }

    @Override
    public String BlogHasType() {
        List<Blog> list=blogRepository.findAll();
        String type="";
        for (Blog b : list){
            if (b.getType().getId()!=null){
                type += b.getType().getId()+" ";
            }
        }
        return type;
    }

    @Override
    public String BlogHasTag() {
        List<Blog> list=blogRepository.findAll();
        //String tag="";
        Set<Long> tags=new HashSet<>();
        for(Blog b : list){
            if(b.getTags() != null){
                List<Tag> tagList=b.getTags();
                for (Tag t : tagList) {
                    tags.add(t.getId());
                }
            }
        }
        return tags.toString();
    }

    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {
        return blogRepository.findByQuery(query,pageable);
    }
}
